import type { EventBus } from 'quasar';
import { eventBusKey, MsgType } from 'src/use';
import { inject } from 'vue';
import { useWebStore } from 'src/stores/webStore';
import WebsocketReconnect from 'src/web-socket';

export const useWebSocketInit = () => {
  const bus = inject(eventBusKey) as EventBus<Api.EventBusType>;

  const webStore = useWebStore();
  if (!webStore.isLogin) {
    return;
  }
  const url = process.env.WS_API;
  const ws = new WebsocketReconnect(url, [], {
    minReconnectionDelay: 10000,
    reconnectionDelayGrowFactor: 1.1,
    enableHeartbeat: true,
    debug: false,
  });

  ws.onopen = function () {
    ws.send(JSON.stringify({ tokenVal: webStore.tokenInfo.tokenValue }));
  };
  ws.onclose = function () {};
  ws.onerror = function (error) {
    console.log('web-socket-error :>> ', error);
  };
  ws.onmessage = function (e) {
    const res = JSON.parse(e.data) as Api.MsgVO;
    switch (res.msgType) {
      case 'refreshChat':
        bus.emit(MsgType.refreshChat, res.chatInfoVO);
        break;
      default:
        break;
    }
  };
  ws.onreconnect = function () {};
};
